package com.example.cinema.drawview;

import android.animation.Animator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.example.cinema.R;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class CircleVideoPlayer extends FrameLayout{


    private SurfaceView surfaceView;

    public CircleVideoPlayer(@NonNull Context context) {
        this(context,null);
        Log.i("KKK","初始化");
    }

    public CircleVideoPlayer(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
        Log.i("KKK","初始化");
    }

    private Context context;
    private boolean isfull = false;//是否显示全屏按钮
    public CircleVideoPlayer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Log.i("KKK","初始化");

        TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.PlayerVideo,defStyleAttr,0);
        isfull = array.getBoolean(R.styleable.PlayerVideo_full,true);
        this.context = context;
        init();
    }

    private boolean isv = true;
    private void init() {
        surfaceView = new SurfaceView(context);
        surfaceView.getHolder().addCallback(new Callback());
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
        surfaceView.setLayoutParams(params);
        addView(surfaceView);

        surfaceView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isv)
                {
                    linearLayout.setVisibility(GONE);
                    isv = false;
                }else {
                    linearLayout.setVisibility(VISIBLE);
                    isv = true;
                }
            }
        });
        ////////////////////////

    }
    private String playurl;
    public void SetUrlPlayer(String url)
    {
        this.playurl = url;
    }

    private String coverimg;
    private ImageView imageView;
    private ImageView startImgBtn;
    private ImageView logon;
    private ImageView quan;
    private LinearLayout linearLayout;
    private SeekBar seekBar;
    private TextView totaltext;
    private TextView currttext;
    private ImageView startbtn;
    private ImageView closebtn;
    public void Setimageurl(String url) {
        if (closebtn == null)
        {
            closebtn = new ImageView(context);
            closebtn.setImageResource(R.mipmap.close_w);
            LayoutParams params = new LayoutParams(50,50);
            params.gravity = Gravity.TOP|Gravity.LEFT;
            params.leftMargin = 30;
            params.topMargin = 30;
            closebtn.setLayoutParams(params);
            closebtn.setScaleType(ImageView.ScaleType.FIT_CENTER);
            addView(closebtn);
            closebtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(listener != null)
                    {
                        listener.onClick(v);
                    }
                }
            });
        }


        if (imageView == null) {
            imageView = new ImageView(context);
            Glide.with(imageView).load(url).into(imageView);
            LayoutParams parama = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
            parama.gravity = Gravity.CENTER;
            imageView.setLayoutParams(parama);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            coverimg = url;
            addView(imageView);
        }
        if (startImgBtn == null) {
            startImgBtn = new ImageView(context);
            startImgBtn.setImageDrawable(getResources().getDrawable(R.drawable.player_btn_state));
            startImgBtn.getDrawable().setLevel(1);
            LayoutParams params = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
            params.width = 80;
            params.height = 80;
            params.gravity = Gravity.CENTER;
            startImgBtn.setLayoutParams(params);
            addView(startImgBtn);
        }

        if (logon == null) {
            logon = new ImageView(context);
            logon.setImageDrawable(getResources().getDrawable(R.mipmap.ch));
            LayoutParams paramsa = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
            paramsa.width = 80;
            paramsa.height = 80;
            paramsa.gravity = Gravity.CENTER;
            logon.setLayoutParams(paramsa);
            logon.setVisibility(GONE);
            addView(logon);
        }

        if (linearLayout == null)
        {
            //控制台容器
            linearLayout = new LinearLayout(context);
            LayoutParams layparame = new LayoutParams(MATCH_PARENT,WRAP_CONTENT);
            layparame.gravity = Gravity.BOTTOM;
            linearLayout.setPadding(0,0,0,0);
            linearLayout.setGravity(Gravity.CENTER);
            linearLayout.setLayoutParams(layparame);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            //进度条容器
            seekBar = new SeekBar(context);
            seekBar.setPadding(0,1,0,1);
            seekBar.setThumb(getResources().getDrawable(R.drawable.player_thumb));
            LinearLayout.LayoutParams paramss = new LinearLayout.LayoutParams(MATCH_PARENT,WRAP_CONTENT);
            paramss.bottomMargin = -15;

            seekBar.setThumbOffset(0);
            seekBar.setLayoutParams(paramss);
            linearLayout.addView(seekBar);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if(fromUser)
                    {
                        mediaPlayer.seekTo(progress);
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            //按钮等布局容器
            LinearLayout infolinear = new LinearLayout(context);
            infolinear.setBackgroundColor(Color.parseColor("#34252525"));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MATCH_PARENT,WRAP_CONTENT);
            infolinear.setLayoutParams(params);
            infolinear.setPadding(0,10,10,0);
            //开始按钮
            startbtn = new ImageView(context);
            startbtn.setImageDrawable(getResources().getDrawable(R.drawable.player_btn_state));
            startbtn.getDrawable().setLevel(1);
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(WRAP_CONTENT,WRAP_CONTENT);
            params1.height = 80;
            params1.width = 100;
            params1.gravity = Gravity.LEFT;
            startbtn.setLayoutParams(params1);
            infolinear.addView(startbtn);
            //开始按钮点击
            startbtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(isstate)
                    {
                        Log.i("PPPP","暂停");
                        mediaPlayer.pause();
                        startbtn.getDrawable().setLevel(1);
                        startImgBtn.getDrawable().setLevel(1);
                        isstate = false;
                    }else {
                        Log.i("PPPP","播放");
                        mediaPlayer.start();
                        startbtn.getDrawable().setLevel(2);
                        startImgBtn.getDrawable().setLevel(2);
                        isstate = true;
                    }

                }
            });

            //时间显示
            LinearLayout textlinear = new LinearLayout(context);
            LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(WRAP_CONTENT,MATCH_PARENT);
            params2.weight = 1;
            params2.gravity = Gravity.CENTER|Gravity.LEFT;
            textlinear.setGravity(Gravity.CENTER|Gravity.LEFT);
            textlinear.setLayoutParams(params2);
            textlinear.setPadding(20,0,20,0);
            //总时间
            totaltext = new TextView(context);
            totaltext.setText("00:00:00");
            totaltext.setTextSize(10);
            totaltext.setTextColor(Color.parseColor("#ffffff"));
            textlinear.addView(totaltext);
            //分割
            TextView tv  = new TextView(context);
            tv.setText("/");
            tv.setTextSize(10);
            tv.setTextColor(Color.parseColor("#ffffff"));
            tv.setPadding(5,0,5,0);
            textlinear.addView(tv);
            //当前时间
            currttext = new TextView(context);
            currttext.setText("00:00:00");
            currttext.setTextSize(10);
            currttext.setTextColor(Color.parseColor("#ffffff"));
            textlinear.addView(currttext);
            infolinear.addView(textlinear);

            //全屏
            quan = new ImageView(context);
            quan.setImageDrawable(getResources().getDrawable(R.mipmap.all));
            LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(WRAP_CONTENT,MATCH_PARENT);
            params3.width = 80;
            params3.height = 80;
            params3.gravity = Gravity.CENTER|Gravity.RIGHT;
            quan.setLayoutParams(params3);
            infolinear.addView(quan);
            if(!isfull)
            {
                quan.setVisibility(GONE);
            }
            quan.setOnClickListener(new OnClickListener() {
                @Override//全屏点击
                public void onClick(View v) {
                    if(fulllistener!=null)
                    {
                        int state = getResources().getConfiguration().orientation;
                        fulllistener.fullClickState(state);
                    }

                }
            });
            linearLayout.addView(infolinear);
            addView(linearLayout);
            linearLayout.setVisibility(GONE);
            linearLayout.setVisibility(GONE);
        }
    }

    //外调接口
    public interface OnClodeClickListener{
        void onClick(View view);
    }
    private OnClodeClickListener listener;
    public void SetOnCloseClickListener(OnClodeClickListener listener)
    {
        this.listener = listener;
    }

    //全屏点击接口
    public interface OnFullClickListener{
        void fullClickState(int state);//全屏回调事件
    }
    //外调方法
    private OnFullClickListener fulllistener;
    public void setOnFullClickListener(OnFullClickListener listener)
    {
        this.fulllistener = listener;
    }


    private IjkMediaPlayer mediaPlayer;
    private int w =0;
    private int h =0;
    private int width = 0;
    private int heigh = 0;
    private Thread thread;//状态监听
    public void loadVideo()
    {
        startbtn.getDrawable().setLevel(2);
        linearLayout.setVisibility(VISIBLE);
        imageView.setVisibility(GONE);
        startImgBtn.setVisibility(GONE);
        logon.setVisibility(GONE);
        if(surfaceView==null)
        {
            surfaceView = new SurfaceView(context);
            surfaceView.getHolder().addCallback(new Callback());
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
            surfaceView.setLayoutParams(params);
            addView(surfaceView);
        }
        if(playurl == null)
        {
            return;
        }

        if(mediaPlayer != null)
        {
            mediaPlayer.release();
        }
        mediaPlayer = new IjkMediaPlayer();

        try {
            mediaPlayer.setDataSource(playurl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.setDisplay(surfaceView.getHolder());
        mediaPlayer.prepareAsync();
        mediaPlayer.start();
        //播放器信息侦听
        mediaPlayer.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
                if(infolistener!=null)
                {
                    infolistener.PlayerInfo(iMediaPlayer.getDuration());
                    seekBar.setMax((int) mediaPlayer.getDuration());
                }
                seekBar.setMax((int) mediaPlayer.getDuration());
                String time = Convert(mediaPlayer.getDuration());
                totaltext.setText(time);
                return false;
            }
        });
        //准备准听器
        mediaPlayer.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer iMediaPlayer) {

                width = getMeasuredWidth();
                heigh = getMeasuredHeight();
                Log.i("JJJ", "高度1:" + heigh);
                int videowidth = iMediaPlayer.getVideoWidth();
                int videoheigh = iMediaPlayer.getVideoHeight();
                Log.i("JJJ", "宽度" + videowidth);
                Log.i("JJJ", "高度" + videoheigh);
                int hh = heigh - videoheigh;
                int ss = Math.abs(hh);
                if (hh < 0)
                {
                    h = heigh;
                    w = videowidth - ss;
                }
                if(hh>0)
                {
                    h = heigh;
                    w = videowidth + ss;
                }
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
                params.height = h;
                params.width  = w;

                params.gravity = Gravity.CENTER;
                Log.i("RRRR",h+"");
                Log.i("RRRR",h+"");
                surfaceView.setLayoutParams(params);
                mediaPlayer.setDisplay(surfaceView.getHolder());
                imageView.setVisibility(GONE);
                startImgBtn.setVisibility(GONE);
                logon.setVisibility(GONE);
            }
        });
        //帧监听
        mediaPlayer.setOnBufferingUpdateListener(new IMediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {

            }
        });
        //状态消息
        mediaPlayer.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer iMediaPlayer) {
                Log.i("AAAA","状态");
            }
        });
        //控制器事件
        mediaPlayer.setOnControlMessageListener(new IjkMediaPlayer.OnControlMessageListener() {
            @Override
            public String onControlResolveSegmentUrl(int i) {
                Log.i("CCC",i+"");
                return null;
            }
        });
        //播放错误
        mediaPlayer.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                Toast.makeText(context,"视频发生错误",Toast.LENGTH_LONG).show();
                isstate = false;
                imageView.setVisibility(GONE);
                startImgBtn.setVisibility(GONE);
                logon.setVisibility(GONE);
                return false;
            }
        });


        thread = new Thread(new TaskAsyn());
        thread.start();
    }
    //线程判断是否缓冲状态
    private boolean isstate = true;
    class TaskAsyn implements Runnable{

        @Override
        public void run() {
            long position = 0;
            while (isstate)
            {
                Log.i("KKK",position+"进度1");
                Log.i("KKK", mediaPlayer.getCurrentPosition()+"进度2");
                if(position == mediaPlayer.getCurrentPosition())
                {

                    Message message = new Message();
                    message.what = 10086;
                    handler.sendMessage(message);
                    position = mediaPlayer.getCurrentPosition();
                }else {
                   Message message = new Message();
                   message.what = 10085;
                   handler.sendMessage(message);
                   position = mediaPlayer.getCurrentPosition();
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 10086:
                    Log.i("KKKKK","缓冲中");
                    logon.setVisibility(VISIBLE);
                    logon.animate().rotationBy(360)
                            .setInterpolator(new LinearInterpolator())
                            .setDuration(1000).start();
                    break;
                case 10085:
                    startbtn.getDrawable().setLevel(2);
                    startImgBtn.getDrawable().setLevel(2);
                    imageView.setVisibility(GONE);
                    startImgBtn.setVisibility(GONE);
                    logon.setVisibility(GONE);
                    break;
            }
            String tim = Convert(mediaPlayer.getCurrentPosition());
            currttext.setText(tim);
        }
    };
    //影片时长
    public long duration;
    //播放/继续
    public void startplay()
    {
        if(mediaPlayer != null)
        {

            mediaPlayer.start();

            startImgBtn.getDrawable().setLevel(2);
            startbtn.getDrawable().setLevel(2);
        }


        isstate = true;
    }
    //暂停播放
    public void pauseplay()
    {
        if(mediaPlayer!=null)
        {
            mediaPlayer.pause();
            startImgBtn.getDrawable().setLevel(1);
            startbtn.getDrawable().setLevel(1);
        }

        isstate = false;
    }
    //停止播放
    public void  stopplay()
    {
        if(mediaPlayer!= null)
        {
            mediaPlayer.release();
            startImgBtn.getDrawable().setLevel(1);
            startbtn.getDrawable().setLevel(1);
        }

        isstate = false;

        imageView.setVisibility(VISIBLE);
        startImgBtn.setVisibility(VISIBLE);
        logon.setVisibility(GONE);
    }
    //获取播放状态
    public boolean getplaystate(){
        return mediaPlayer.isPlaying();
    }

    //设置进度
    public void setProess(long duration)
    {
        mediaPlayer.seekTo(duration);

    }
    //全屏
    public void allquan()
    {

        int videowidth = mediaPlayer.getVideoWidth();
        int videoheigh = mediaPlayer.getVideoHeight();

        int ww = width = getResources().getDisplayMetrics().widthPixels;
        int hh = heigh = getResources().getDisplayMetrics().heightPixels;

        ViewGroup.LayoutParams pram = getLayoutParams();
        pram.height = ww;
        pram.width = hh;
        this.setLayoutParams(pram);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
        int h1 = width - videoheigh;
        int ss = Math.abs(h1);
        int hv = 0;
        int wv = 0;
        if (h1 < 0)
        {
            hv = width;
            wv = videowidth - ss;
        }
        if(hh>0)
        {
            hv = width;
            wv = videowidth + ss;
        }
        params.height = hv;
        params.width  = wv;
        Log.i("WWWW",wv+"");
        Log.i("WWWW",hv+"");
        params.gravity = Gravity.CENTER;
        Log.i("RRRR",h+"");
        Log.i("RRRR",h+"");
        surfaceView.setLayoutParams(params);
        mediaPlayer.setDisplay(surfaceView.getHolder());
    }
    //缩屏
    public void narrow(int height)
    {
        int www = getResources().getDisplayMetrics().widthPixels;
        int hhh = getResources().getDisplayMetrics().heightPixels;
        Log.d("GGGG", "narrow: www"+www);
        Log.d("GGGG", "narrow: hhh"+hhh);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = height;
        params.width = hhh;
        setLayoutParams(params);

        FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(MATCH_PARENT,WRAP_CONTENT);
        params1.height = height;
        params1.width = hhh;
        surfaceView.setLayoutParams(params1);
        mediaPlayer.setDisplay(surfaceView.getHolder());
    }

    //时间转字符串
    private String Convert(long time)
    {
        long tm = time /1000;
        int s = (int) (tm % 60);
        int m = (int) (tm/60);
        int h = (int) (tm/60/60);
        String ss,mm,hh;
        hh = (h<10)?"0"+h:h+"";
        mm = (m<10)?"0"+m:m+"";
        ss = (s<10)?"0"+s:s+"";
        return hh+":"+mm+":"+ss;
    }
    /**********************************/
    class Callback implements SurfaceHolder.Callback{

        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            if(mediaPlayer == null)
            {
                return;
            }
            if (mediaPlayer.isPlaying())
            {
                mediaPlayer.setDisplay(surfaceView.getHolder());
            }
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            if(mediaPlayer!=null)
            {
                mediaPlayer.setDisplay(surfaceView.getHolder());
            }

        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

        }
    }

    /**********************************/
    public  interface VideoPlayerInfo{
        void PlayerInfo(long total);//视频长度

    }

    private VideoPlayer.VideoPlayerInfo infolistener;
    public void setOnVideoPlayerInfo(VideoPlayer.VideoPlayerInfo info)
    {
        infolistener = info;
    }
}
